#include "logindialog.h"
#include "ui_logindialog.h"
#include "mainwindow.h"
#include "global.h"
#include <QSqlDatabase>
#include <QSqlQueryModel>
#include <QSettings>
#include <QSqlQuery>

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    initUi();
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::initUi()
{
    if (MainWindow::connectToDb()) {
        QSqlQueryModel *m = new QSqlQueryModel(this);
        m->setQuery("SELECT user_id FROM user_t", QSqlDatabase::database());
        ui->userCombo->setModel(m);
        ui->userCombo->setCurrentText(QSettings().value(LOGIN_USER).toString());
    }
}

void LoginDialog::on_okBtn_clicked()
{
    QSqlQuery q("SELECT password FROM user_t WHERE user_id=?", QSqlDatabase::database());
    q.addBindValue(ui->userCombo->currentText());
    if (q.exec() && q.next()) {
        if (q.value(0).toString() == ui->pwdEdit->text()) {
            QSettings().setValue(LOGIN_USER, ui->userCombo->currentText());
            accept();
        } else {
            ui->statusLabel->setText(tr("Incorrect password."));
        }
    } else {
        ui->statusLabel->setText(tr("Database error."));
    }
}
